package com.euond.permission.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.euond.common.core.dto.ResultDto;
import com.euond.common.core.dto.SerachMapDto;
import com.euond.common.core.exception.ServiceException;
import com.euond.common.core.service.impl.BaseServiceImpl;
import com.euond.permission.entities.Resource;
import com.euond.permission.entities.ResourcePermission;
import com.euond.permission.entities.Role;
import com.euond.permission.entities.RoleResource;
import com.euond.permission.mapper.RoleResourceMapper;
import com.euond.permission.service.RoleResourceService;
import com.euond.permission.service.UserPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2017/7/24.
 */
@Service
public class RoleResourceServiceImpl extends BaseServiceImpl<RoleResourceMapper,RoleResource> implements RoleResourceService {

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Autowired
    private UserPermissionService userPermissionService;

    // @Autowired
    // private ResourcePermissionService resourcePermissionService;

    /*
    * 重写基类insert方法
    */
    @Override
    @Transactional
    public boolean insert(RoleResource roleResource) {
         super.insert(roleResource);
         try{
             //同时增加用户权限
             userPermissionService.addUserPermissionByRoleResource(roleResource);
             return true;
         }catch (ServiceException e) {
             return false;
         }
    }

    /*
* 重写基类insertBatch方法
*/
    @Override
    @Transactional
    public boolean insertBatch(List<RoleResource> entityList) {
        super.insertBatch(entityList);
        try{
            for(int i=0;i<entityList.size();i++){
                //同时增加用户权限
                userPermissionService.addUserPermissionByRoleResource(entityList.get(i));
            }
            return true;
        }catch (ServiceException e) {
            return false;
        }
    }

    /*
    * 重写基类deleteBatchIds方法
    */
    @Override
    @Transactional
    public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
        try{
            //删除角色资源关系前先删除对应的用户权限
            List<RoleResource> roleResourceList=selectBatchIds(idList);
            for(int i=0;i<roleResourceList.size();i++){
                //同时更新用户权限
                userPermissionService.updateUserPermissionByResource(roleResourceList.get(i).getResourceId(),roleResourceList.get(i).getCompanyId());
            }
            return super.deleteBatchIds(idList);
        }catch (ServiceException e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean delete(Wrapper<RoleResource> wrapper){
        try{
            //删除角色资源关系前先删除对应的用户权限
            List<RoleResource> roleResourceList=selectList(wrapper);
            for(int i=0;i<roleResourceList.size();i++){
                //同时更新用户权限
                userPermissionService.updateUserPermissionByResource(roleResourceList.get(i).getResourceId(),roleResourceList.get(i).getCompanyId());
            }
            return super.delete(wrapper);
        }catch (ServiceException e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteById(Serializable id){
        try{
            //删除角色资源关系前先删除对应的用户权限
            RoleResource roleResource=selectById(id);
            //同时更新用户权限
            userPermissionService.updateUserPermissionByResource(roleResource.getResourceId(),roleResource.getCompanyId());
            return super.deleteById(id);
        }catch (ServiceException e) {
            return false;
        }
    }

    /**
     * 查询角色资源（分页）
     *
     * @param searchParams
     */
    public ResultDto findRoleResources(Map<String,Object> searchParams){
        RoleResource roleResource=new RoleResource();
        SerachMapDto serachMapDto=new SerachMapDto(searchParams,roleResource);
        Page<RoleResource> page=new Page(serachMapDto.getPageCurrent(),serachMapDto.getPageSize());
        //假如存在需要扩展特殊的条件内容，则可以(UserRole)serachMapDto.getObject()重新赋值
        page.setRecords(roleResourceMapper.findRoleResources(page,(RoleResource)serachMapDto.getObject()));
        ResultDto resultDto=new ResultDto("0","seccess",page.getRecords(),page.getTotal());
        return resultDto;

    }

    /**
     * 按角色查找已分配角色的资源
     * @param searchParams
     * @return
     */
    public ResultDto findRoleAvailableResources(Map<String,Object> searchParams){
        RoleResource roleResource=new RoleResource();
        SerachMapDto serachMapDto=new SerachMapDto(searchParams,roleResource);
        Page<RoleResource> page=new Page(serachMapDto.getPageCurrent(),serachMapDto.getPageSize());
        //假如存在需要扩展特殊的条件内容，则可以(UserRole)serachMapDto.getObject()重新赋值
        roleResource=(RoleResource)serachMapDto.getObject();
        page.setRecords(roleResourceMapper.findRoleAvailableResources(page,roleResource.getRoleId(),roleResource.getResourceName()));
        ResultDto resultDto=new ResultDto("0","seccess",page.getRecords(),page.getTotal());
        return resultDto;
    };

    /**
     * 按角色查找未分配角色的资源
     * @param searchParams
     * @return
     */
    public ResultDto findRoleNotAvailableResources(Map<String,Object> searchParams){
        RoleResource roleResource=new RoleResource();
        SerachMapDto serachMapDto=new SerachMapDto(searchParams,roleResource);
        Page<Resource> page=new Page(serachMapDto.getPageCurrent(),serachMapDto.getPageSize());
        //假如存在需要扩展特殊的条件内容，则可以(UserRole)serachMapDto.getObject()重新赋值
        roleResource=(RoleResource)serachMapDto.getObject();
        List<Resource> resourceList=roleResourceMapper.findRoleNotAvailableResources(page,roleResource.getRoleId(),roleResource.getResourceName());
        for(int i=0;i<resourceList.size();i++){
            Long resourceId=resourceList.get(i).getId();
            //List<ResourcePermission> resourcePermissionList=resourcePermissionService.findResourcePermissionByResourceId(resourceId);
            List<ResourcePermission> resourcePermissionList=null;
            resourceList.get(i).setPermissionList(resourcePermissionList);
        }
        page.setRecords(resourceList);
        ResultDto resultDto=new ResultDto("0","seccess",page.getRecords(),page.getTotal());
        return resultDto;
    };

    /**
     * 按角色Id查找用户角色关系
     * @param roleId
     * @return
     */
    public List<RoleResource> findRoleResourcesByRoleId(Long roleId){
        EntityWrapper entityWrapper=new EntityWrapper<RoleResource>();
        entityWrapper.eq("role_id",roleId);

        return selectList(entityWrapper);
    }

    /**
     * 按角色Id删除角色资源
     * @param roleId
     * @return
     */
    public void deleteRoleResourceByRoleId(Long roleId){
        EntityWrapper entityWrapper=new EntityWrapper();
        entityWrapper.eq("role_id",roleId);
        delete(entityWrapper);
    }

    /**
     * 按角色Id查找角色资源
     * @param roleId
     * @return
     */
    public List<RoleResource> findRoleResourceByRoleId(Long roleId){
        EntityWrapper entityWrapper=new EntityWrapper();
        entityWrapper.eq("role_id",roleId);
        return selectList(entityWrapper);
    }
}
